<template>
  <div class="evaluate">
    <div class="score-title">
      <span class="title">评分</span>
      <div class="pattern">
        <p
          :class="{ active: pattern === 'standard' }"
          @click="choosePattern('standard')"
        >
          标准打分模式
        </p>
        <p
          :class="{ active: pattern === 'weight' }"
          @click="choosePattern('weight')"
        >
          权重打分模式
        </p>
      </div>
    </div>
    <Title name="标准分" :score="qualityItemTotal" />
    <div v-for="(item, index) in qualityItem" :key="item.id" class="item">
      <p>
        <span class="label">{{ item.name }}</span>
        <span v-if="pattern === 'weight'" class="separate weight">|</span>
        <span v-if="pattern === 'weight'" class="weight"
          >{{ typeof item.weight === "number" ? item.weight : 0 }}%</span
        >
      </p>
      <el-input-number
        v-model="item.score"
        :max="defaultQualityScore[index]"
        :precision="2"
        controls-position="right"
      />
    </div>
    <Title name="附加分" :score="qualityAppendItemTotal" />
    <div v-for="(item, index) in qualityAppendItem" :key="item.id" class="item">
      <p>
        <span class="label">{{ item.name }}</span>
        <span v-if="pattern === 'weight'" class="separate weight">|</span>
        <span v-if="pattern === 'weight'" class="weight"
          >{{ typeof item.weight === "number" ? item.weight : 0 }}%</span
        >
      </p>
      <el-input-number
        v-model="item.score"
        :max="defaultQualityAppendScore[index]"
        :precision="2"
        controls-position="right"
      />
    </div>
    <div class="total-score">
      <span class="label">总分:</span>
      <span class="num">{{ total }}</span>
    </div>
    <p class="comment">质检点评</p>
    <el-input
      type="textarea"
      v-model="comments"
      placeholder="请输入您要点评的内容"
      :rows="4"
    />
    <div v-if="rescore" class="btns">
      <el-button size="mini" @click="cancelReScore">取消</el-button>
      <el-button
        type="primary"
        size="mini"
        style="margin-left: 10px"
        @click="saveScore"
        >确定</el-button
      >
    </div>
    <div v-else class="btns">
      <el-button type="primary" size="mini" @click="getNextRecord"
        >跳过并评分下一条</el-button
      >
      <el-button
        type="primary"
        size="mini"
        style="margin-left: 10px"
        @click="saveScore"
        >保存并评分下一条</el-button
      >
      <el-button style="margin-left: 10px" size="mini" @click="initData"
        >重置</el-button
      >
    </div>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import configTable from '@/components/globalTool/resizeTable/index.vue'
import Title from '@/views/qualityCheck/result/components/title.vue'
import { plus, times, divide } from '@/utils/number-precision'
import { deepClone, commonAction } from '@/utils/common'
@Component({
  name: 'scoreDetail',
  components: {
    configTable,
    Title
  }
})
export default class ScoreDetail extends Vue {
  [x: string]: any
  // ----------------传入属性-----------------------
  @Prop({ default: '' }) public sessionId!: string; // 会话ID
  @Prop({ default: '' }) public scoringId!: string; // 评分ID
  @Prop({ default: '' }) public applyQualityTime!: string; // 提交质检会话时间

  @Prop({ default: () => ({}) }) public templateConfig!: any; // 模板配置数据

  @Prop({ default: false }) private rescore
  // ----------------内部属性-----------------------
  private pattern: any = 'standard'

  // 质检项目
  private qualityItem: any = []

  // 附加质检项
  private qualityAppendItem: any = []

  // 点评内容
  private comments: string = '';

  // 当前模板ID
  private qualityConfigId: string = '';

  // 分数段配置

  private scoreRangeList: any = [];
  // ----------------计算属性-----------------------
  // 致命值
  get specialNum () {
    let rtNum = 1;
    this.qualityItem.some((item) => {
      if (this.pattern === 'standard') {
        if (item.special && item.score < 60) {
          rtNum = 0;
          return true;
        }
      } else {
        if (item.special && divide(times(item.score, item.weight), 100) < 60) {
          rtNum = 0;
          return true;
        }
      }
    })
    return rtNum;
  }

  // 标准总分
  get qualityItemTotal () {
    if (this.qualityItem && this.qualityItem.length > 0) {
      return this.qualityItem.map((item) => {
        if (this.pattern === 'weight') {
          const weight = typeof item.weight === 'number' ? item.weight : 0;
          return typeof item.score === 'number' ? divide(times(item.score, weight), 100) : 0
        } else {
          return typeof item.score === 'number' ? item.score : 0;
        }
      }).reduce((n, m) => {
        return plus(n, m);
      });
    } else {
      return 0;
    }
  }

  // 标准附加总分
  get qualityAppendItemTotal () {
    if (this.qualityAppendItem && this.qualityAppendItem.length > 0) {
      return this.qualityAppendItem.map((item) => {
        if (this.pattern === 'weight') {
          const weight = typeof item.weight === 'number' ? item.weight : 0;
          return typeof item.score === 'number' ? divide(times(item.score, weight), 100) : 0
        } else {
          return typeof item.score === 'number' ? item.score : 0;
        }
      }).reduce((n, m) => plus(n, m));
    } else {
      return 0;
    }
  }

  // 总分
  get total () {
    return plus(this.qualityItemTotal, this.qualityAppendItemTotal) * this.specialNum;
  }

  // 分数段

  get scoreRange () {
    let returnText = '';
    if (this.scoreRangeList && this.scoreRangeList.length) {
      this.scoreRangeList.some((item) => {
        const low = typeof item.low === 'number' ? item.low : 0;
        const high = typeof item.high === 'number' ? item.high : 0;
        if (low <= this.total && this.total <= high) {
          returnText = item.name;
          return true;
        }
      })
    }
    return returnText;
  }

  // 默认标准分列表
  get defaultQualityScore () {
    return this.templateConfig[this.rescore ? 'qualityItemScore' : 'qualityItem'].map((item) => {
      if (Object.keys(item).includes('maxScore')) {
        return typeof item.maxScore === 'number' ? item.maxScore : 0;
      } else {
        return typeof item.score === 'number' ? item.score : 0;
      }
    })
  }

  // 默认附加分列表
  get defaultQualityAppendScore () {
    if (this.rescore) { // 重新评分
      return this.templateConfig.qualityAppendItemScore.map((item) => {
        if (Object.keys(item).includes('maxScore')) {
          return typeof item.maxScore === 'number' ? item.maxScore : 0;
        } else {
          return typeof item.score === 'number' ? item.score : 0;
        }
      })
    } else {
      return this.templateConfig.qualityAppendItem.map((item) => {
        if (item.oprateScoreItem !== 'add') {
          if (Object.keys(item).includes('maxScore')) {
            return typeof item.maxScore === 'number' ? item.maxScore * -1 : 0
          } else {
            return typeof item.score === 'number' ? item.score * -1 : 0
          }
        } else {
          if (Object.keys(item).includes('maxScore')) {
            return typeof item.maxScore === 'number' ? item.maxScore : 0;
          } else {
            return typeof item.score === 'number' ? item.score : 0;
          }
        }
      })
    }
  }
  // ----------------监听方法-----------------------

  @Watch('sessionId', { immediate: true })
  private sessionIdChange (newId: any) {
    if (newId) {
      this.initData();
    }
  }

  @Watch('templateConfig', { deep: true })
  private templateConfigChange () {
    this.choosePattern('standard');
    this.initData();
  }

  // ----------------调用方法-----------------------
  // 保存评分

  private saveScore () {
    console.log(this.qualityItem);
    console.log(this.qualityAppendItem);
    const params = {
      url: '/im-center/action/quality/saveGradeChat',
      method: 'POST',
      data: {
        name: this.templateConfig.name,
        _id: this.scoringId,
        gradeScore: this.total,
        comments: this.comments,
        chatSessionId: this.sessionId,
        qualityConfigId: this.qualityConfigId,
        qualityItemScore: this.qualityItem,
        qualityAppendItemScore: this.qualityAppendItem,
        scoreType: this.pattern === 'standard' ? '1' : '2',
        scoreRange: this.scoreRange,
        scoreRangeList: this.scoreRangeList,
        saveGradeChatMore: this.rescore
      }
    }
    commonAction(params).then(res => {
      if (res.success) {
        if (this.rescore) {
          this.$message.success('重新评分成功')
          this.$emit('offReScore')
        } else {
          this.getNextRecord();
        }
      }
    })
  }

  private getNextRecord () {
    const params = {
      url: '/im-center/action/quality/nextQualitySession',
      method: 'POST',
      data: {
        _id: this.scoringId,
        applyQualityTime: this.applyQualityTime
      }
    }
    commonAction(params).then(res => {
      if (res.success) {
        if (res.data) {
          this.$emit('next', {
            sessionId: res.data.data._id,
            createTime: res.data.applyQualityTime,
            visitorId: res.data.data.visitorId,
            scoringID: res.data._id
          })
        } else {
          this.$message.info('没有需要评分记录！')
        }
      }
    })
  }

  // 初始化评分模板数据
  private initData () {
    if (this.rescore) { // 重新评分
      this.$set(this, 'qualityItem', deepClone(this.templateConfig.qualityItemScore));
      this.$set(this, 'qualityAppendItem', deepClone(this.templateConfig.qualityAppendItemScore));
      this.$set(this, 'scoreRangeList', this.templateConfig.scoreRangeList);
      this.pattern = this.templateConfig.scoreType === '1' ? 'standard' : 'weight'
      this.qualityConfigId = this.templateConfig.qualityConfigId
      this.comments = this.templateConfig.comments
    } else {
      let filterQualityAppendItem = []
      if (this.templateConfig.qualityAppendItem) {
        filterQualityAppendItem = deepClone(this.templateConfig.qualityAppendItem).map((item) => {
          if (item.oprateScoreItem !== 'add') {
            item.score = item.score * -1;
          }
          return item;
        })
      }
      this.qualityConfigId = this.templateConfig._id;
      this.comments = '';
      this.$set(this, 'qualityItem', deepClone(this.templateConfig.qualityItem));
      this.$set(this, 'qualityAppendItem', filterQualityAppendItem);
      this.$set(this, 'scoreRangeList', this.templateConfig.scoreRange);
    }
  }

  // ----------------生命周期-----------------------

  private choosePattern (val: any) {
    this.pattern = val
  }

  private cancelReScore () {
    this.$emit('offReScore')
  }
}
</script>
<style lang="stylus" scoped>
.evaluate
  width 100%
  padding 0 24px
  .btns
    width 100%
    text-align right
    margin-top 20px
  .comment
    color #303753
    margin 20px 0 10px
  .total-score
    display flex
    justify-content space-between
    padding 20px 0
    border-bottom 1px solid #E7E9ED
    .label
      font-weight 600
      color #303753
    .num
      font-size 18px
      font-weight 600
      color #008BEE
      font-family PingFang SC
  .item
    padding 6px 12px
    height 40px
    border 1px solid #E7E9ED
    border-radius 4px
    display flex
    justify-content space-between
    align-items center
    margin-bottom 10px
    &:last-child
      margin-bottom 0
    p
      flex 1
      .label
        color #303753
      .separate
        margin 0 10px
      .weight
        color #767E91
    >>> .el-input-number
      width 100px
      .el-input-number__increase, .el-input-number__decrease
        width 20px
        background #fff
        font-size 8px
        color #303753
  .score-title
    height 78px
    border-bottom 1px solid #E7E9ED
    margin-bottom 20px
    display flex
    justify-content space-between
    align-items center
    .title
      font-size 14px
      font-weight 600
      color #303753
    .pattern
      width 206px
      height 32px
      background #EFF3F8
      border-radius 4px
      padding 2px
      font-weight 600
      color #767E91
      display flex
      p
        width 100px
        height 28px
        text-align center
        line-height 28px
        border-radius 4px
        cursor pointer
      .active
        background #FFFFFF
        color #303753
</style>
